package com.sendpo.zjx.sendpo.activity;

import android.Manifest;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.ActivityCompat;
import android.support.v4.app.FragmentManager;
import android.support.v7.app.AppCompatActivity;
import android.text.TextUtils;
import android.view.View;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.amap.api.location.AMapLocation;
import com.amap.api.location.AMapLocationClientOption;
import com.amap.api.location.AMapLocationListener;
import com.google.gson.Gson;
import com.sendpo.zjx.sendpo.R;
import com.sendpo.zjx.sendpo.application.MyApplication;
import com.sendpo.zjx.sendpo.domain.UserDomain;
import com.sendpo.zjx.sendpo.fragment.IndexMainFragment;
import com.sendpo.zjx.sendpo.fragment.MainYanchuFragment;
import com.sendpo.zjx.sendpo.fragment.MyselfMainFragment;
import com.sendpo.zjx.sendpo.fragment.WatchStoreAllFragment;
import com.sendpo.zjx.sendpo.fragment.WatchStoreMainFragment;
import com.sendpo.zjx.sendpo.fragment.WuliuMainFragment;
import com.sendpo.zjx.sendpo.net.HttpCode;
import com.sendpo.zjx.sendpo.net.HttpUrl;
import com.sendpo.zjx.sendpo.services.AmapLocationService;
import com.sendpo.zjx.sendpo.table.User;
import com.sendpo.zjx.sendpo.utils.Tools;
import com.sendpo.zjx.sendpo.utils.Xutils;
import com.sendpo.zjx.sendpo.zxing.activity.CaptureActivity;
import com.zaaach.citypicker.CityPickerActivity;

import org.json.JSONException;
import org.json.JSONObject;
import org.xutils.common.Callback;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import ch.ielse.view.imagewatcher.ImageWatcher;

/**
 * Created by 朱俊鑫 on 2017/7/4.
 * information 主界面
 */

public class MainActivity extends AppCompatActivity implements  ImageWatcher.OnPictureLongPressListener, AMapLocationListener {
    private static final int REQUEST_CODE_PICK_CITY = 0;
    public static final int REQUEST_SCAN = 103;
    public static final int REQUEST_CODE_REQUEST_PERMISSION = 104;
    public long currenttime = 0;
    @BindView(R.id.radio_index_iv)
    ImageView radioIndexIv;
    @BindView(R.id.radio_index_tv)
    TextView radioIndexTv;
    @BindView(R.id.radio_index)
    RelativeLayout radioIndex;
    @BindView(R.id.radio_store_iv)
    ImageView radioStoreIv;
    @BindView(R.id.radio_store_tv)
    TextView radioStoreTv;
    @BindView(R.id.radio_store)
    RelativeLayout radioStore;
    @BindView(R.id.radio_jianqi_iv)
    ImageView radioJianqiIv;
    @BindView(R.id.radio_jianqi_tv)
    TextView radioJianqiTv;
    @BindView(R.id.radio_jianqi)
    RelativeLayout radioJianqi;
    @BindView(R.id.radio_fujinweistore_iv)
    ImageView radioFujinweistoreIv;
    @BindView(R.id.radio_fujinweistore_tv)
    TextView radioFujinweistoreTv;
    @BindView(R.id.radio_fujinweistore)
    RelativeLayout radioFujinweistore;
    @BindView(R.id.radio_myself_iv)
    ImageView radioMyselfIv;
    @BindView(R.id.radio_myself_tv)
    TextView radioMyselfTv;
    @BindView(R.id.radio_myself)
    RelativeLayout radioMyself;
    @BindView(R.id.bottom)
    RelativeLayout bottom;
    @BindView(R.id.mainviewpager)
   public FrameLayout mainviewpager;
      public IndexMainFragment indexMainFragment;
   public WatchStoreMainFragment watchStoreAllFragment;
   public WuliuMainFragment wuliuMainFragment;
    public MainYanchuFragment yanchumanfragment;
      public MyselfMainFragment myselfMainFragment;
    @BindView(R.id.v_image_watcher)
  public  ImageWatcher vImageWatcher;
    public static  final int REQUEST_NOLOGIN=1013;
    public AmapLocationService amapLocationService;
    public double userLongitude = 0;
    public double userLatitude = 0;
    public String userProvince = "";
    public String userCity = "";
    public String userArea = "";
    public String userAddress = "";

    public FragmentManager fm;
    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        ButterKnife.bind(this);
        Tools.initStatus(this, R.color.black);
        initComponent();
      //  initRequestPermission();
        MyApplication.addActivity(this);
        initFragment();
    }

    public void initComponent() {
        vImageWatcher.setTranslucentStatus(0); // 如果是透明状态栏，你需要给ImageWatcher标记 一个偏移值，以修正点击ImageView查看的启动动画的Y轴起点的不正确
        vImageWatcher.setErrorImageRes(R.mipmap.error_picture); // 配置error图标 如果不介意使用lib自带的图标，并不一定要调用这个API
        vImageWatcher.setOnPictureLongPressListener(this); // 长按图片的回调，你可以显示一个框继续提供一些复制，发送等功能


    }
    public AMapLocationClientOption getDefaultAmapLocationOptions(){
        AMapLocationClientOption mLocationOption=null;
        if(mLocationOption==null){
            mLocationOption = new AMapLocationClientOption();
            //设置定位模式为AMapLocationMode.Hight_Accuracy，高精度模式。
            mLocationOption.setLocationMode(AMapLocationClientOption.AMapLocationMode.Battery_Saving);
            mLocationOption.setLocationCacheEnable(true);
            mLocationOption.setOnceLocation(true);
            mLocationOption.setOnceLocationLatest(false);
            //设置是否返回地址信息（默认返回地址信息）
            mLocationOption.setNeedAddress(true);
            //设置是否强制刷新WIFI，默认为true，强制刷新。
            mLocationOption.setWifiScan(true);
            mLocationOption.setInterval(2000);
            //单位是毫秒，默认30000毫秒，建议超时时间不要低于8000毫秒。
            mLocationOption.setHttpTimeOut(20000);
        }
        return  mLocationOption;
    }

    @Override
    protected void onStart() {
        super.onStart();
        if(amapLocationService==null){
            System.out.println("*****************amapLocationService is null");
            amapLocationService=new AmapLocationService(this);
            amapLocationService.setmLocationOption(getDefaultAmapLocationOptions());
            amapLocationService.registerListener(this);
            amapLocationService.start();
        }else{
            System.out.println("*****************amapLocationService isnot null");
            amapLocationService=new AmapLocationService(this);
            amapLocationService.setmLocationOption(getDefaultAmapLocationOptions());
            amapLocationService.registerListener(this);
            amapLocationService.start();
            amapLocationService.start();
        }

    }
    @OnClick({R.id.radio_index, R.id.radio_store, R.id.radio_jianqi, R.id.radio_fujinweistore, R.id.radio_myself})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.radio_index:
                setStyleItem(0);
                break;
            case R.id.radio_fujinweistore:
                setStyleItem(1);
                break;
            case R.id.radio_jianqi:
                setStyleItem(2);
                break;
            case R.id.radio_store:
                setStyleItem(3);
                break;

            case R.id.radio_myself:
                List<User> userList= Xutils.queryAll(getApplication(), User.class);
                  if(userList==null||userList.size()==0){
                     Tools.redirectActivity(this,LoginActivity.class);
                return;
            }
                setStyleItem(4);
                break;
        }
    }

    public void setStyleItem(int position) {
        switch (position) {
            case 0:
                radioIndexIv.setImageResource(R.mipmap.home_press);
                radioIndexTv.setTextColor(getResources().getColor(R.color.default_theme));
                radioStoreIv.setImageResource(R.mipmap.shop1);
                radioStoreTv.setTextColor(getResources().getColor(R.color.default_gray));
                radioJianqiIv.setImageResource(R.mipmap.self_support);
                radioJianqiTv.setTextColor(getResources().getColor(R.color.default_gray));
                radioFujinweistoreIv.setImageResource(R.mipmap.webshop);
                radioFujinweistoreTv.setTextColor(getResources().getColor(R.color.default_gray));
                radioMyselfIv.setImageResource(R.mipmap.me);
                radioMyselfTv.setTextColor(getResources().getColor(R.color.default_gray));
          fm.beginTransaction().show(indexMainFragment)
          .hide(wuliuMainFragment)
                  .hide(watchStoreAllFragment)
                  .hide(yanchumanfragment)
                  .hide(myselfMainFragment)
                  .commitAllowingStateLoss();

                break;
            case 1:
                radioIndexIv.setImageResource(R.mipmap.home_nopress);
                radioIndexTv.setTextColor(getResources().getColor(R.color.default_gray));
                radioFujinweistoreIv.setImageResource(R.mipmap.webshop_press);
                radioFujinweistoreTv.setTextColor(getResources().getColor(R.color.default_theme));
                radioJianqiIv.setImageResource(R.mipmap.self_support);
                radioJianqiTv.setTextColor(getResources().getColor(R.color.default_gray));
                radioStoreIv.setImageResource(R.mipmap.shop1);
                radioStoreTv.setTextColor(getResources().getColor(R.color.default_gray));
                radioMyselfIv.setImageResource(R.mipmap.me);
                radioMyselfTv.setTextColor(getResources().getColor(R.color.default_gray));
                fm.beginTransaction().show(wuliuMainFragment)
                        .hide(indexMainFragment)
                        .hide(watchStoreAllFragment)
                        .hide(yanchumanfragment)
                        .hide(myselfMainFragment)
                        .commitAllowingStateLoss();

                break;

            case 2:
                radioIndexIv.setImageResource(R.mipmap.home_nopress);
                radioIndexTv.setTextColor(getResources().getColor(R.color.default_gray));
                radioStoreIv.setImageResource(R.mipmap.shop1);
                radioStoreTv.setTextColor(getResources().getColor(R.color.default_gray));
                radioFujinweistoreIv.setImageResource(R.mipmap.webshop);
                radioFujinweistoreTv.setTextColor(getResources().getColor(R.color.default_gray));
                radioJianqiIv.setImageResource(R.mipmap.self_support_press);
                radioJianqiTv.setTextColor(getResources().getColor(R.color.default_theme));
                radioMyselfIv.setImageResource(R.mipmap.me);
                radioMyselfTv.setTextColor(getResources().getColor(R.color.default_gray));
                fm.beginTransaction().show(watchStoreAllFragment)
                        .hide(indexMainFragment)
                        .hide(wuliuMainFragment)
                        .hide(yanchumanfragment)
                        .hide(myselfMainFragment)
                        .commitAllowingStateLoss();
                break;
            case 3:
                radioIndexIv.setImageResource(R.mipmap.home_nopress);
                radioIndexTv.setTextColor(getResources().getColor(R.color.default_gray));
                radioFujinweistoreIv.setImageResource(R.mipmap.webshop);
                radioFujinweistoreTv.setTextColor(getResources().getColor(R.color.default_gray));
                radioJianqiIv.setImageResource(R.mipmap.self_support);
                radioJianqiTv.setTextColor(getResources().getColor(R.color.default_gray));
                radioStoreIv.setImageResource(R.mipmap.shop1_press);
                radioStoreTv.setTextColor(getResources().getColor(R.color.default_theme));
                radioMyselfIv.setImageResource(R.mipmap.me);
                radioMyselfTv.setTextColor(getResources().getColor(R.color.default_gray));
                fm.beginTransaction()
                        .show(yanchumanfragment)
                        .hide(indexMainFragment)
                        .hide(wuliuMainFragment)
                        .hide(watchStoreAllFragment)
                        .hide(myselfMainFragment)
                        .commitAllowingStateLoss();
                break;
            case 4:

                radioIndexIv.setImageResource(R.mipmap.home_nopress);
                radioIndexTv.setTextColor(getResources().getColor(R.color.default_gray));
                radioFujinweistoreIv.setImageResource(R.mipmap.webshop);
                radioFujinweistoreTv.setTextColor(getResources().getColor(R.color.default_gray));
                radioJianqiIv.setImageResource(R.mipmap.self_support);
                radioJianqiTv.setTextColor(getResources().getColor(R.color.default_gray));
                radioStoreIv.setImageResource(R.mipmap.shop1);
                radioStoreTv.setTextColor(getResources().getColor(R.color.default_gray));
                radioMyselfIv.setImageResource(R.mipmap.me_press);
                radioMyselfTv.setTextColor(getResources().getColor(R.color.default_theme));
                fm.beginTransaction()
                        .show(myselfMainFragment)
                        .hide(indexMainFragment)
                        .hide(wuliuMainFragment)
                        .hide(watchStoreAllFragment)
                        .hide(yanchumanfragment)
                        .commitAllowingStateLoss();
                break;
        }
    }

    @Override
    public void onPictureLongPress(ImageView v, String url, int pos) {

    }

    public void initFragment(){
         fm=getSupportFragmentManager();
        indexMainFragment=new IndexMainFragment();
        wuliuMainFragment=new WuliuMainFragment();
        watchStoreAllFragment=new WatchStoreMainFragment();
        yanchumanfragment=new MainYanchuFragment();
        myselfMainFragment=new MyselfMainFragment();
        fm.beginTransaction().add(R.id.mainviewpager,indexMainFragment,"IndexMainFragment")
                .hide(indexMainFragment)
                .add(R.id.mainviewpager,wuliuMainFragment,"WuliuMainFragment")
                .hide(wuliuMainFragment)
                .add(R.id.mainviewpager,watchStoreAllFragment,"WatchStoreMainFragment")
                .hide(watchStoreAllFragment)
                .add(R.id.mainviewpager,yanchumanfragment,"MainYanchuFragment")
                .hide(watchStoreAllFragment)
                .add(R.id.mainviewpager,myselfMainFragment,"MyselfMainFragment")
                .hide(myselfMainFragment)
                .commit();
         setStyleItem(0);


    }

    @Override
    public void onLocationChanged(AMapLocation aMapLocation) {
        System.out.println("*********************************getAddress:"+aMapLocation.getAddress());
        if (amapLocationService == null || aMapLocation == null) {
           Toast.makeText(getApplicationContext(),"定位失败，请检查网络和手机权限或者是否打开GPS",Toast.LENGTH_SHORT).show();
            return;
        }
        userLongitude=aMapLocation.getLongitude();
        userLatitude=aMapLocation.getLatitude();
        userProvince=aMapLocation.getProvince();
        userCity=aMapLocation.getCity();
        userArea=aMapLocation.getDistrict();
        int index=aMapLocation.getAddress().lastIndexOf(userProvince+userCity+userArea);
        userAddress=aMapLocation.getAddress().substring(index+(userProvince+userCity+userArea).length(),aMapLocation.getAddress().length());
        changeLocation(userLongitude + "", userLatitude + "", userProvince, userCity, userArea, userAddress);
    }



    //自动定位
    public void changeLocation(String userLongitude, String userLatitude,
                               String userProvince, String userCity, String userArea,
                               String userAddress) {

        List<User> users = Xutils.queryAll(getApplication(), User.class);
        if (users == null || users.size() == 0) {
            return;
        }
        Map<String, String> map = new HashMap<>();
        map.put("userId", users.get(0).getUserId() + "");
        map.put("userLongitude", userLongitude);
        map.put("userLatitude", userLatitude);
        map.put("userProvince", userProvince);
        map.put("userCity", userCity);
        map.put("userArea", userArea);
        map.put("userAddress", userAddress);
        Xutils.POST(HttpUrl.usermodifylocation, map, new Callback.CommonCallback<String>() {
            @Override
            public void onSuccess(String result) {
                try {
                    JSONObject json = new JSONObject(result);
                    switch (json.getInt("state")) {
                        case HttpCode.SUCCESS:
                            webUserServer();
                            break;
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }

            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {

            }

            @Override
            public void onCancelled(CancelledException cex) {

            }

            @Override
            public void onFinished() {

            }
        });


    }



    public void webUserServer() {
        final List<User> userList = Xutils.queryAll(getApplication(), User.class);
        if (userList == null || userList.size() == 0) {
            return;
        }
        Map<String, String> map = new HashMap<>();
        map.put("userId", userList.get(0).getUserId() + "");
        Xutils.POST(HttpUrl.queryuserbyid, map, new Callback.CommonCallback<String>() {
            @Override
            public void onSuccess(String result) {
                Gson gson = new Gson();
                UserDomain userDomain = gson.fromJson(result, UserDomain.class);
                switch (userDomain.getState()) {
                    case HttpCode.SUCCESS:
                        User user = userDomain.getData();
                        user.setId(userList.get(0).getId());
                        Xutils.update(getApplication(), user);
                        break;
                }
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {

            }

            @Override
            public void onCancelled(CancelledException cex) {

            }

            @Override
            public void onFinished() {

            }
        });
    }



    @Override
    public void onBackPressed() {
        if (System.currentTimeMillis() - currenttime > 2000) {
            currenttime = System.currentTimeMillis();
            Toast.makeText(this.getApplicationContext(), "再按一次退出", Toast.LENGTH_SHORT).show();
        } else {
            super.onBackPressed();
            System.exit(0);
        }
    }
    //重写onActivityResult方法


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (resultCode != RESULT_OK) {
            return;
        }
        switch (requestCode) {
            case REQUEST_SCAN:
                Bundle bundle = data.getExtras();
                String scanResult = bundle.getString("result");
               if(TextUtils.isEmpty(scanResult)){
            Toast.makeText(getApplicationContext(),"没有内容",Toast.LENGTH_SHORT).show();
                   return;
               }
                try {
                    JSONObject jsonObject=new JSONObject(scanResult);
                    int merchandiseId=jsonObject.getInt("merchandiseId");
                    Map<String,Object> map=new HashMap<>();
                    map.put("merchandiseId",merchandiseId);
                  Tools.redirectActivity(this, GeneicStoreInfoActivity.class,map);
                } catch (JSONException e) {
                    e.printStackTrace();
                    Toast.makeText(getApplicationContext(),"数据解析失败",Toast.LENGTH_SHORT).show();
                return;
                }

                break;
            case REQUEST_CODE_PICK_CITY:
                if (data != null) {
                    String city = data.getStringExtra(CityPickerActivity.KEY_PICKED_CITY);
                    Toast.makeText(MainActivity.this.getApplicationContext(), "切换位置:" + city, Toast.LENGTH_SHORT).show();
                 indexMainFragment.merchandisebylocation(city);
                    indexMainFragment.merchandisebyremai(userCity);
                    indexMainFragment. merchandisebydajianjia(userCity);
                    indexMainFragment.pagenow=1;
                    indexMainFragment.iniTuijian(userCity,indexMainFragment.pagenow);
                }
                break;
            case REQUEST_NOLOGIN:
                SharedPreferences sp = Tools.getSharedPreference(this, Tools.CONFIG);
                SharedPreferences.Editor editor = sp.edit();
                editor.remove(Tools.NICKNAME);
                editor.remove(Tools.PASSWORD);
                editor.remove(Tools.CHECK_AUTOLOGIN);
                editor.commit();
                Xutils.DropTable(this.getApplication(), User.class);
                setStyleItem(0);
              //  finish();
                break;
        }
    }

    //打开选择城市
    public void openSelecterLocation() {
        startActivityForResult(new Intent(MainActivity.this, CityPickerActivity.class),
                REQUEST_CODE_PICK_CITY);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
    if(amapLocationService!=null){
        amapLocationService.stop();
        amapLocationService.unregisterListener(this);

     }
    }

    public void initRequestPermission() {
        ActivityCompat.requestPermissions(this,new String[]{
                Manifest.permission.ACCESS_COARSE_LOCATION,
                Manifest.permission.ACCESS_FINE_LOCATION,
                Manifest.permission.READ_EXTERNAL_STORAGE,
                Manifest.permission.WRITE_EXTERNAL_STORAGE,
                Manifest.permission.CAMERA,
                Manifest.permission.RECORD_AUDIO,
                Manifest.permission.ACCESS_NETWORK_STATE,
                Manifest.permission.ACCESS_WIFI_STATE
        },REQUEST_CODE_REQUEST_PERMISSION);
    }




    //扫描
    public void openCamera() {
        Intent openCameraIntent = new Intent(MainActivity.this, CaptureActivity.class);
        startActivityForResult(openCameraIntent, REQUEST_SCAN);
    }

    public void completeExitLogin(){
        Intent openCameraIntent = new Intent(MainActivity.this,UserSetActivity.class);
      startActivityForResult(openCameraIntent,REQUEST_NOLOGIN);
    }

}
